package inutan.game.prop;

import inutan.common.context.FlowContext;
import inutan.data.Resource.Type;
import inutan.data.Role.RoleLevelVal;
import inutan.game.business.GameFlowContext;
import inutan.game.entity.UserInfo;
import inutan.game.entity.prop.BaseItemInfo;
import inutan.game.event.model.RoleLevelUpEvent;
import inutan.game.storage.StorageContext;
import org.ricks.common.event.EventBus;
import org.ricks.common.exception.ServerBootstrapException;
import org.ricks.orm.OrmContext;
import java.util.List;
import java.util.Optional;

public class PlayerExpOperate implements OperatePropInterface{
    @Override
    public List<BaseItemInfo> props(GameFlowContext context) {
        UserInfo userInfo = OrmContext.me().uniqueCacheLoad(UserInfo.class, context.getUserId()).get();
        return List.of(new BaseItemInfo(Type.PLAYEREXP, Type.PLAYEREXP , userInfo.getExp()));
    }

    @Override
    public void useProp(GameFlowContext context, List<BaseItemInfo> item) {
        throw new ServerBootstrapException("玩家经验无法消耗！");
    }

    @Override
    public List<BaseItemInfo> addProp(GameFlowContext context, List<BaseItemInfo> item) {
        UserInfo userInfo = OrmContext.me().uniqueCacheLoad(UserInfo.class,context.getUserId()).get();
        int oldLevel = userInfo.getLevel();
        int exp = userInfo.getExp() + item.stream().mapToInt(x -> x.getCount()).sum();
        boolean iscont = true;
        Optional<RoleLevelVal> dataOpt = StorageContext.tables().getTbRoleLevel().getDataList().stream().filter(x -> x.level == oldLevel + 1).findFirst();
        while (iscont) {
            if (dataOpt.isPresent()) {
                RoleLevelVal data = dataOpt.get();
                if (data.needExp <= exp) {
                    exp -= data.needExp;
                    userInfo.setLevel(data.level);
                    dataOpt = StorageContext.tables().getTbRoleLevel().getDataList().stream().filter( x -> x.level == data.level + 1).findFirst();
                } else iscont = false;
                userInfo.setExp(exp);
            } else iscont = false;
        }
        if (userInfo.getLevel() != oldLevel) {
            //升级 触发任务事件
            EventBus.me().publish(new RoleLevelUpEvent(context, userInfo.getLevel(), oldLevel));
            //通知前端?
        }
        OrmContext.me().update(userInfo);
        return List.of();
    }

    @Override
    public boolean checkItemNum(GameFlowContext context, List<BaseItemInfo> itemInfo) {
        throw new ServerBootstrapException("玩家经验无法check !");
    }
}
